package com.chats.filter;

import com.alibaba.fastjson.JSONObject;
import com.chats.common.Result;
import com.chats.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
@Component
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        log.info(request.getMethod());

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 定义不需要处理的请求路径
        String[] urls = new String[] {
                "/user/login",
                "/user/logout",
                "/user/register",
                "/socket/**"
        };

        // 判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        // 如果不需要处理，则直接放行
        if(check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 判断登录状态，如果已登录，则直接放行


        // 获取请求头中的令牌（token）
        String token = request.getHeader("Authorization");
        log.info("用户token：{}", token);

        if(!StringUtils.hasLength(token)) {
            log.info("请求头token为空，返回未登录的信息");
            Result error = Result.error("用户未登录");
            //手动转换对象
            String noLogin = JSONObject.toJSONString(error);
            // 跨域处理
            cors(request, response);
            response.getWriter().write(noLogin);
            return;
        }

        // 解析token，如果解析失败，返回错误结果（未登录）
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) { // jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录的错误信息");
            Result error = Result.error("用户未登录");
            // 手动转换对象
            String noLogin = JSONObject.toJSONString(error);
            // 跨域处理
            cors(request, response);
            response.getWriter().write(noLogin);
            // 设置401响应码
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }

        // 放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match) {
                return true;
            }
        }
        return false;
    }

    /**
     * 跨域处理
     */
    private void cors(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    }
}